<template>
    <div class="safe_view">
        <el-input class="ipt" placeholder="用户名" @focus="userErr=''" v-model="userName">
            <i slot="prefix" class="el-input__icon el-icon-user"></i>
        </el-input>
        <span class="err" v-show="userErr">{{userErr}}</span>
        <el-input class="ipt" placeholder="密码" @focus="pwdErr=''" v-model="password" type="password">
            <i slot="prefix" class="el-input__icon el-icon-key"></i>
        </el-input>
        <span class="err" v-show="pwdErr">{{pwdErr}}</span>
        <el-button type="success" @click="register">登录</el-button>
    </div>
</template>
<script>
export default {
    data(){
        return{
            userName:"",
            password:"",
            userErr:"",
            pwdErr:""
        }
    },
    methods:{
        register:async function(){
            var patt=/^[\w\u4e00-\u9fa5]{6,12}$/;
            if(!patt.test(this.userName)){
                this.userErr="只能包含数字、字母、下划线、汉字6-12位";
                return false;
            }

            var patt2=/^\w{6,12}$/;
            if(!patt2.test(this.password)){
                this.pwdErr="只能包含数字、字母、下划线6-12位";
                return false;
            }

            var res=await this.$ajax("/login?userName="+this.userName+"&password="+this.password);
            if(res.data.code){
                this.$message({
                    type:"success",
                    message:"登录成功,欢迎"+res.data.userName
                })
                setTimeout(()=>{
                    if(this.$route.query.url){
                        this.$router.replace(decodeURIComponent(this.$route.query.url));
                    }else{
                        this.$router.replace("/");
                    }
                },1000)
                this.$store.commit("update_token",res.data.token);
            }else{
                this.$message.error("用户名或密码错误");
            }
            this.userName=this.userErr=this.password=this.pwdErr="";
        }
    },
    created(){
        // 刷新
        this.$store.commit("type_flag",!this.$route.meta.type_flag);
    }
}
</script>
<style scoped>
    .safe_view{
        width: 400px;
        margin-top:80px
    }
    .safe_view .ipt{
        margin-top:20px
    }
    .safe_view>>> button{
        margin:0 auto;
        display: block;
        width: 100%;
        margin-top:30px
    }
    .err{
        color:red;
        font-size:12px
    }
</style>